<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="(tm, index) in tradeMarkList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" rows="4" placeholder="SPU描述" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload :action="`${baseURL}/admin/product/fileUpload`" list-type="picture-card"
          :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handlerSuccess" :file-list="spuImageList">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttr.length}个未选择`" v-model="attrIdAndName">
          <el-option :label="item.name" :value="`${item.id}:${item.name}`" v-for="item in unSelectSaleAttr" :key="item.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndName" @click="addSaleAttr">添加销售属性</el-button>
        <el-table style="width: 100%" border="" :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80px" align="center">
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="160px">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{row, $index}">
                <el-tag
                  :key="tag.id"
                  v-for="(tag,index) in row.spuSaleAttrValueList"
                  closable
                  :disable-transitions="false"
                  @close="row.spuSaleAttrValueList.splice(index, 1)"
                  >
                  {{tag.saleAttrValueName}}
                </el-tag>
                <!-- "
                  -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @blur="handleInputConfirm(row)"
                  @keyup.enter.native="handleInputConfirm(row)"

                >
                </el-input>
                 <!-- @click="showInput" -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="120px">
            <template slot-scope="{row,$index}">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>

      </el-form-item>

    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      dialogImageUrl: '',
      dialogVisible: false,
      //存储spu信息属性
      spu: {
        category3Id: 0,
        description: "",
        tmId: '',
        spuName: "",
        spuImageList: [
          // {
          //   "id": 0,
          //   "imgName": "string",
          //   "imgUrl": "string",
          //   "spuId": 0
          // }
        ],
        spuSaleAttrList: [
          // {
          //   "baseSaleAttrId": 0,
          //   "id": 0,
          //   "saleAttrName": "string",
          //   "spuId": 0,
          //   "spuSaleAttrValueList": [
          //     {
          //       "baseSaleAttrId": 0,
          //       "id": 0,
          //       "isChecked": "string",
          //       "saleAttrName": "string",
          //       "saleAttrValueName": "string",
          //       "spuId": 0
          //     }
          //   ]
          // }
        ]
      },
      tradeMarkList: [], //存储全部品牌数据
      spuImageList: [], //存储spu图片
      saleAttrList: [], //存储平台中全部的销售属性
      attrIdAndName: '', //收集未选择的销售属性Id和名字

    }
  },
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.spuImageList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件上传成功时的钩子
    handlerSuccess(response, file, fileList){
      // console.log(response);
      // console.log(file);
      // console.log(fileList);
      // this.spuImageList = fileList
      if(response.code == 200){
        this.spuImageList.push(file)
      }else{
        this.$message('上传图片出错！')
      }
    },
    //点击修改时候，获取spu信息
    async initSpuData(spu) {
      //获取spu信息的数据
      let spuResult = await this.$API.spu.reqGetSpuInfoById(spu.id)
      if (spuResult.code == 200) {
        this.spu = spuResult.data
      }
      // 获取全部品牌数据
      let tradeMarkResult = await this.$API.spu.reqTrademarkList()
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data
      }

      // 获取Spu的图片
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id)
      if (spuImageResult.code == 200) {
        let listArr = spuImageResult.data
        listArr.forEach(item=>{
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = listArr
      }
      // 获取平台中全部的销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data
      }
    },

    // 点击添加按钮时，发请求
    async addSpuData(category3Id){
      // // 清理数据
      // this.spu = {
      //   category3Id: category3Id,
      //   description: "",
      //   tmId: '',
      //   spuName: "",
      //   spuImageList: [
      //   ],
      //   spuSaleAttrList: [
      //   ]
      // }
      // this.spuImageList = []


      // 获取全部品牌数据
      let tradeMarkResult = await this.$API.spu.reqTrademarkList()
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data
      }
      // 获取平台中全部的销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data
      }

      this.spu.category3Id = category3Id


    },



    // 添加新的销售属性
    addSaleAttr(){
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndName.split(':')
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
      }
      this.spu.spuSaleAttrList.push(newSaleAttr)
      //别忘了清空select的选择
      this.attrIdAndName = ''

    },

    //添加按钮的回调
    showInput(row){
      this.$set(row,'inputVisible', true)
      this.$set(row, 'inputValue', '')
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    // el-input失去焦点的事件
    handleInputConfirm(row){
      const {baseSaleAttrId, saleAttrName, spuId, inputValue} = row
      // 新增的销售属性值的名称不能为空
      if(inputValue.trim()==''){
        this.$message('输入的属性值不能为空')
        row.inputVisible = false;
        row.inputValue = '';
        return
      }

      // 属性值不能重复  用every时，if(!flag)
      // let flag = row.spuSaleAttrValueList.every(item=>item.saleAttrValueName.trim() != inputValue.trim())
      let flag = row.spuSaleAttrValueList.some(item=>item.saleAttrValueName.trim() == inputValue.trim())
      if(flag){
        this.$message('输入的属性值不能重复')
        row.inputVisible = false;
        row.inputValue = '';
        return
      }

      const tempObject = {
        baseSaleAttrId,
        // isChecked: null,
        saleAttrName,
        saleAttrValueName: inputValue.trim(),
        spuId
      }
      row.spuSaleAttrValueList.push(tempObject);

      row.inputVisible = false;
      row.inputValue = '';

    },
    // 保存按钮的回调
    async addOrUpdateSpu(){
      //整理参数,需要整理照片墙的数据
      this.spu.spuImageList = this.spuImageList.map(item=>{
        return {
          imgName: item.name,
          imgUrl: item.response?item.response.data:item.imgUrl,
          id: item.id,
          spuId: item.spuId
        }
      })

      //发送请求
      const result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
      if(result.code == 200){ //代表保存成功
        this.$emit('changeScene', {scene:'0', flag:this.spu.id?'edit':'add'})
        this.$message({type:'success', message:'保存成功'})
        // 清理数据
        Object.assign(this._data, this.$options.data())
      }

    },

    //取消按钮
    cancel(){
      this.$emit('changeScene', {scene:'0', flag:'edit'})
      // 清理数据
      Object.assign(this._data, this.$options.data())
    }



  },
  computed: {
    // 计算出还未选择的销售属性
    unSelectSaleAttr(){
      return this.saleAttrList.filter((item)=>{
        return this.spu.spuSaleAttrList.every(item2=>{
          return item.name != item2.saleAttrName
        })
      })
    }
  },

}
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
